'use strict'

const fs = require('fs')
const {spawn} = require('child_process')

/**
 * 根据主版本号、次版本号、小版本号转数字逆排序。
 * 只保留同一主版本号最新的。
 *
 * */

let install_path = '/usr/local/mno'

let version_path = `${install_path}/versions`

let fsp = fs.promises

let node_name_regex = /^node\-v/

let arch_name = 'x64'
switch (process.arch) {
  case 'arm':
  case 'arm64':
    arch_name = 'arm64'
    break

  case 'loong64':
    arch_name = 'loong64'
    break
}

function parseName(n) {
  let ns = n.split('-')[1]
  let vs = ns.substring(1).split('.')
  return {
    name: n,
    v: ns.substring(1),
    vs: [
      parseInt(vs[0]),
      parseInt(vs[1]),
      parseInt(vs[2])
    ]
  }
}

;(async () => {
  let flist = await fsp.readdir(install_path, {withFileTypes: true})
  let nodes = []

  for (let f of flist) {
    if (!f.isDirectory()) continue

    if (!node_name_regex.test(f.name)) {
      continue
    }

    nodes.push(parseName(f.name))
  }

  let compare_v = (av, bv) => {
    if (av > bv) return -1
    if (av < bv) return 1

    return 0
  }

  nodes.sort((a, b) => {
    let inds = [0, 1, 2]
    let r
    for (let i of inds) {
      r = compare_v(a.vs[i], b.vs[i])
      if (r) return r
    }
    return 0
  })

  if (nodes.length <= 0) return ''

  let main_version = {}
  let delete_list = []
  for (let n of nodes) {
    if (!main_version[n.vs[0]]) {
      main_version[n.vs[0]] = true
    } else {
      delete_list.push(n.v)
    }
  }
  
  console.log(nodes[0].v)
  for (let a of delete_list) {
    console.log(a)
  }

})();
